package com.baseweb.webadmin.core.util;

import com.baseweb.webadmin.core.model.pojo.Resc;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by dengsy on 2017-06-25.
 */
public class TreeResc {
    List<Resc> nodes = new ArrayList<>();

    public TreeResc() {

    }

    public TreeResc(List<Resc> nodes) {
        super();
        this.nodes = nodes;
    }

    public List<Resc> buildTree(List<Resc> nodes) {

        TreeResc treeBuilder = new TreeResc(nodes);

        return treeBuilder.buildTree();
    }

    // 构建树形结构
    public List<Resc> buildTree() {
        List<Resc> treeNodes = new ArrayList<>();
        List<Resc> rootNodes = getRootNodes();
        for (Resc rootNode : rootNodes) {
            buildChildNodes(rootNode);
            treeNodes.add(rootNode);
        }
        return treeNodes;
    }

    // 递归子节点
    public void buildChildNodes(Resc node) {
        List<Resc> children = getChildNodes(node);
        if (!children.isEmpty()) {
            for (Resc child : children) {
                buildChildNodes(child);
            }
            node.setRescList(children);
        }
    }

    // 获取父节点下所有的子节点
    public List<Resc> getChildNodes(Resc pnode) {
        List<Resc> childNodes = new ArrayList<>();
        for (Resc n : nodes) {
            if (pnode.getId().equals(n.getFatherId())) {
                childNodes.add(n);
            }
        }
        return childNodes;
    }

    // 判断是否为根节点
    public boolean rootNode(Resc node) {
        boolean isRootNode = true;
        for (Resc n : nodes) {
            if (node.getFatherId().equals(n.getId())) {
                isRootNode = false;
                break;
            }
        }
        return isRootNode;
    }

    // 获取集合中所有的根节点
    public List<Resc> getRootNodes() {
        List<Resc> rootNodes = new ArrayList<>();
        for (Resc n : nodes) {
            if (rootNode(n)) {
                rootNodes.add(n);
            }
        }
        return rootNodes;
    }
}
